<template>
  <div class="container" ref="mainCon">
    <!-- 标题 -->
    <topTitle :titleText="titleText" :titleExplain="titleExplain"></topTitle>
    <!-- 搜索 -->
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="公司名称" class="row-padding-bottom">
              <el-input
                placeholder="请输入公司名称"
                clearable
                v-model="filterField.companyName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="9" :xl="6">
            <el-form-item
              label="统一社会信用代码"
              class="row-padding-bottom"
              label-width="135px"
            >
              <el-input
                placeholder="请输入统一社会信用代码"
                clearable
                v-model="filterField.uscc"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-form-item>
            <!-- <el-button type="primary" icon="icon iconfont iconchazhao1" class="commonBtn" @click="searchList"></el-button> -->
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <!-- <el-form-item v-show="isShowAdd">
                        <el-button class="commonBut saveBtn funComBut" icon="icon iconfont icontianjia" @click="toAdd">
                            <span class="opetareText">添加</span>
                        </el-button>
                    </el-form-item> -->
        </el-form>
      </el-row>
      <!-- 表格 -->
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icontianjia"
            @click="toAdd"
          >
            <span class="opetareText">添加</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          @sort-change="sortChange"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <!-- <el-table-column prop="companyName" label="公司名称" align="center" :formatter="formatTd"></el-table-column>  -->
          <el-table-column label="公司名称" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="uscc"
            label="统一社会信用代码"
            align="center"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="openAccountCount"
            label="统一专户数"
            sortable="custom"
            align="center"
            :formatter="formatTd"
            min-width="180"
          ></el-table-column>
          <el-table-column
            prop="expensesTotal"
            label="总支出（元）"
            sortable="custom"
            align="center"
            :formatter="formatTd"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="balanceTotal"
            label="余额（元）"
            sortable="custom"
            align="center"
            :formatter="formatTd"
            min-width="160"
          ></el-table-column>
          <el-table-column label="操作" align="left" width="130" fixed="right">
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-if="isShowDetail"
                @click="seeDetail(scope.row)"
                >详情</el-link
              >
              <el-link type="primary" @click="toUpdate(scope.row)"
                >修改</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- 分页 -->
        <Pagination
          ref="pagination"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
      <!-- 新增弹窗 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="formVisible"
        :close-on-click-modal="false"
        @close="closeDialog"
        custom-class="brand-dialog-min-width"
        width="640px"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <el-form
          :model="formData"
          :rules="formRules"
          ref="formData"
          class="mrT8"
          label-width="120px"
        >
          <el-form-item label="企业名称：" prop="companyId">
            <el-select
              class="dialogSingleInp"
              ref="companySearch"
              v-model="formData.companyId"
              v-bind:disabled="selectDisabled"
              clearable
              filterable
              placeholder="请输入企业名称进行搜索"
              @change="ChangeSearch"
            >
              <el-option
                v-for="(item, index) in companyOptions"
                :key="index"
                :label="item.companyName"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="统一社会信用代码：" class="agreementBox">
            <span v-if="companyUscc" class="color333">{{ companyUscc }}</span>
            <span v-else class="color999">选择企业后自动带出</span>
          </el-form-item>
          <el-form-item
            label="是否允许开设多个统一专户："
            prop="isOpenAccount"
            class="agreementBox"
          >
            <el-radio-group v-model="formData.isOpenAccount">
              <el-radio label="1" style="width: 120px">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="是否只添加专户区域内的项目："
            prop="isAreaProject"
            class="agreementBox"
          >
            <el-radio-group v-model="formData.isAreaProject">
              <el-radio label="1" style="width: 120px">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="cancelEdit('formData')" class="cancel"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click.native="addProject('formData')"
            class="save"
            :loading="isSaveLoading"
            >保存</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import scrollTable from '@/mixin/scrollTable.js'
export default {
  name: 'enterpriseAccountManage',
  mixins: [scrollTable],
  data() {
    return {
      titleText: '企业专户管理', //监察端
      titleExplain:
        '设置项目:该企业作为施工方关联的项目由监察部门控制是否可以使用 同一专户账号,可对部分项目开放该特权',
      requestUrl: 'api-acc/companyaccount/expand/findpagebymonitor',
      //表格数据
      tableList: [],
      isShow: false, //列表加载
      loading: false,
      filterField: {
        companyName: '',
        uscc: '',
      },
      pageSize: 20,
      pageNo: 1,
      formVisible: false,
      isSaveLoading: false, // 弹框保存loading
      id: '',
      companyOptions: [], //企业名称下拉框
      projectSelect: '',
      item: '', //当前选中项
      companyUscc: '',
      total: 0, //企业名称总数
      pageSizeNumber: 20,
      formData: {
        companyId: '',
        // socialId: "",
        isOpenAccount: '',
        isAreaProject: '',
        id: '',
      },
      state: '',
      formRules: {
        companyId: [
          {
            required: true,
            message: '企业名称不能为空',
            trigger: 'change',
          },
        ],
        isOpenAccount: [
          {
            required: true,
            message: '是否允许开设多个统一专户不能为空',
            trigger: 'change',
          },
        ],
        isAreaProject: [
          {
            required: true,
            message: '是否只添加专户区域内的项目不能为空',
            trigger: 'change',
          },
        ],
      },
      isShowAdd: '',
      isShowDetail: '',
      addOrUpdate: '',
      dialogTitle: '',
      selectDisabled: false,
    }
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('companyaccount:add') > -1
    this.isShowDetail =
      this.$store.state.buttonLimitsArr.indexOf('companyaccount:detail') > -1
  },
  mounted() {},
  activated() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    //查看详情
    seeDetail(row) {
      this.$router.push({
        path: '/home/yiChangCustomRequirements/accountManageTab',
        name: 'accountManageTab',
        query: {
          id: row.id,
          companyName: row.companyName,
          uscc: row.uscc,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/yiChangCustomRequirements/enterpriseAccountManage',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toAdd() {
      this.dialogTitle = '添加企业'
      this.selectDisabled = false
      this.formVisible = true
      this.companyUscc = ''
      this.addOrUpdate = 'add'
      this.getCompanyList(this.pageNo, this.pageSizeNumber)
    },
    getCompanyList(pageNo, pageSizeNumber, val) {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/findpbcompanylist',
        data: {
          pageNo: pageNo,
          pageSize: pageSizeNumber,
          companyName: val,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.companyOptions = response.data.result
              this.total = response.data.result.total
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    ChangeSearch() {
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.companySearch.blur()
      })
      this.item = this.companyOptions[this.formData.companyId]
      if (this.item) {
        this.companyUscc = this.item.uscc
      } else {
        this.companyUscc = ''
      }
    },
    //选择企业
    visibleChangeProject(val) {
      if (!this.formData.companyId && this.formData.companyId !== 0) {
        if (val) {
          this.pageNo = 1
          this.projectSelect = ''
          this.formData.companyId = ''
          this.getCompanyList(
            this.pageNo,
            this.pageSizeNumber,
            this.projectSelect
          )
        }
      } else {
        //手动输入再次打开弹框清空输入值
        // 获取的企业数据索引
        // 选中的企业的具体数据
        if (typeof this.formData.companyId === 'string') {
          this.formData.companyId = ''
        } else {
        }
      }
    },
    selectChange(val) {
      //手动输入掉接口会清空问题下拉框的值，掉完接口再赋值
      this.projectSelect = val
      this.getCompanyList(1, this.pageSizeNumber, val)
      if (typeof this.formData.companyId === 'string') {
        this.formData.companyId = val
      }
      this.formData.companyId = val
      // alert(val)
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      this.getCompanyList(val, this.pageSizeNumber, this.projectSelect)
      this.formData.companyId = ''
      this.companyUscc = ''
    },
    //关闭弹窗
    closeDialog() {
      this.$refs['formData'].resetFields()
    },
    // 弹框取消
    cancelEdit() {
      this.formVisible = false
      this.$refs['formData'].resetFields()
    },
    addProject(formName) {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          if (this.addOrUpdate == 'add') {
            this.submitFormAdd()
          } else {
            this.submitFormUpdate()
          }
        } else {
          return false
        }
      })
    },
    submitFormAdd() {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccountconfig/expand/add',
        data: {
          companyName: this.item.companyName,
          uscc: this.companyUscc,
          isOpenAccount: this.formData.isOpenAccount,
          isAreaProject: this.formData.isAreaProject,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$refs['formData'].resetFields()
            this.formVisible = false
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
    toUpdate(row) {
      this.addOrUpdate = 'update'
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccountconfig/expand/findbyuscc',
        data: {
          companyName: row.companyName,
          uscc: row.uscc,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.formData.companyId = response.data.result.companyName
            this.companyUscc = response.data.result.uscc
            this.formData.isOpenAccount =
              response.data.result.isOpenAccount + ''
            this.formData.isAreaProject =
              response.data.result.isAreaProject + ''
            this.formData.id = response.data.result.id
            this.selectDisabled = true
            this.dialogTitle = '修改权限'
            this.formVisible = true
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.$message.error('请求失败')
        })
    },
    submitFormUpdate() {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccountconfig/expand/edit',
        data: {
          isOpenAccount: this.formData.isOpenAccount,
          isAreaProject: this.formData.isAreaProject,
          id: this.formData.id,
          uscc: this.companyUscc,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$refs['formData'].resetFields()
            this.formVisible = false
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
        })
    },
  },
}
</script>

<style lang="less" scoped>
.mainCon {
  top: 212px;
}
@import '../../../static/css/filterArea.less';
.agreementBox {
  /deep/label {
    line-height: 20px;
  }
}
</style>
